/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.scrumpmt.web;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.primefaces.event.DashboardReorderEvent;
import org.primefaces.model.DashboardColumn;
import org.primefaces.model.DashboardModel;
import org.primefaces.model.DefaultDashboardColumn;
import org.primefaces.model.DefaultDashboardModel;
import org.scrumpmt.domain.Estado;
import org.scrumpmt.domain.Sprint;
import org.scrumpmt.domain.Tarea;
import org.scrumpmt.ejb.EstadoFacade;
import org.scrumpmt.ejb.SprintFacade;
import org.scrumpmt.ejb.TareaFacade;

/**
 *
 * @author agumpg
 */
@ManagedBean(name = "pizarraBean")
@RequestScoped
public class PizarraBean extends BasicBean {

    @EJB
    private EstadoFacade estadoFacade;
    private TareaFacade tareaFacade = lookupTareaFacade();
    private SprintFacade sprintFacade = lookupSprintFacade();
    private ArrayList<Task> tasks;
    private DashboardModel model;
    private String productoId;
    private String sprintId;
    private List<Sprint> sprints;
    private Sprint selectedSprint;

    public PizarraBean() {

        FacesContext context = FacesContext.getCurrentInstance();
        ProductoSeleccionadoBean productoBean = (ProductoSeleccionadoBean) context.getApplication().evaluateExpressionGet(context, "#{productoSeleccionadoBean}", ProductoSeleccionadoBean.class);
        productoId = productoBean.getProductoActual();
        sprintId = productoBean.getSprintActual();

        //productoId = "233";//El producto hay que obtenerlo de la sesion. Cuando se implemente borramos esta linea
        //sprintId = "2"; //El sprint hay que obtenerlo de la sesión o de un combo.

        //Proyecto proyectoAbierto = proyectoFacade.find(Long.parseLong(producto));

        log.log(Level.INFO, "producto y sprint {0}", "P: " + productoId + " S: " + sprintId);

        sprints = sprintFacade.findByProyecto(productoId);

        log.log(Level.INFO, "El producto es {0}", productoId);

        model = new DefaultDashboardModel();
        tasks = new ArrayList<Task>();

        DashboardColumn lstTodo = new DefaultDashboardColumn();
        DashboardColumn lstDoing = new DefaultDashboardColumn();
        DashboardColumn lstDone = new DefaultDashboardColumn();

        List<Tarea> tareas = tareaFacade.findByProyectoAndSprint(productoId, sprintId);

        if (tareas != null && tareas.size() > 0) {
            for (Tarea t : tareas) {
                Task task = new Task();
                task.fromEntity(t);
                tasks.add(task);

                switch (task.getEstado()) {
                    case 1:
                        lstTodo.addWidget(task.getId());
                        break;
                    case 2:
                        lstDoing.addWidget(task.getId());
                        break;
                    case 3:
                        lstDone.addWidget(task.getId());
                        break;
                }
            }
        }

        model.addColumn(lstTodo);
        model.addColumn(lstDoing);
        model.addColumn(lstDone);
    }

    public void handleReorder(DashboardReorderEvent event) {
        // Actualizamos el cambio en la BD
        Tarea tarea = tareaFacade.find(Long.parseLong(event.getWidgetId().substring(3)));
        Estado e = estadoFacade.find(event.getColumnIndex().longValue() + 1);
        tarea.setIdEstadoFk(e);
        switch (event.getColumnIndex()) {
            case 0: //Lista ToDO
                tarea.setFecini(null);
                tarea.setFecfin(null);
                break;
            case 1: //Lista Doing
                tarea.setFecini(new Date());
                if (tarea.getFecfin() != null) {
                    tarea.setFecfin(null);
                }
                break;
            case 2: //Lista Done
                tarea.setFecfin(new Date());
                if (tarea.getFecini() == null) {
                    tarea.setFecini(new Date());
                }
        }

        tareaFacade.edit(tarea);

        // Visualizamos mensaje Growl informativo
        FacesMessage message = new FacesMessage();
        message.setSeverity(FacesMessage.SEVERITY_INFO);
        message.setSummary("Pizarra Actualizada");

        String info = "La tarea \"" + tarea.getDes() + "\" cambia al estado \"" + e.getDes() + "\"";
        message.setDetail(info);
        addMessage(message);
    }

    private void addMessage(FacesMessage message) {
        FacesContext.getCurrentInstance().addMessage(null, message);
    }

    public DashboardModel getModel() {
        return model;
    }

    public void setModel(DashboardModel model) {
        this.model = model;
    }

    public ArrayList<Task> getTasks() {
        return tasks;
    }

    public void setTasks(ArrayList<Task> tasks) {
        this.tasks = tasks;
    }

    public Sprint getSelectedSprint() {
        return selectedSprint;
    }

    public void setSelectedSprint(Sprint selectedSprint) {
        this.selectedSprint = selectedSprint;
    }

    public List<Sprint> getSprints() {
        return sprints;
    }

    public void setSprints(List<Sprint> sprints) {
        this.sprints = sprints;
    }

    private TareaFacade lookupTareaFacade() {
        try {
            Context c = new InitialContext();
            return (TareaFacade) c.lookup("java:global/ScrumPMT/ScrumPMT-ejb/TareaFacade!org.scrumpmt.ejb.TareaFacade");
        } catch (NamingException ne) {
            log.log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }

    private SprintFacade lookupSprintFacade() {
        try {
            Context c = new InitialContext();
            return (SprintFacade) c.lookup("java:global/ScrumPMT/ScrumPMT-ejb/SprintFacade!org.scrumpmt.ejb.SprintFacade");
        } catch (NamingException ne) {
            log.log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }
}
